package com.study.spring.redislock;

import lombok.extern.slf4j.Slf4j;
import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.redisson.spring.starter.RedissonAutoConfiguration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * @author
 * @date 2022年04月30日 9:04
 * @description
 */
@RestController
@Slf4j
@ConditionalOnBean(RedissonAutoConfiguration.class)
public class RedisController {


    @Autowired
    private StringRedisTemplate redisTemplate;


    @Resource
    private Redisson redisson;

    @RequestMapping("/lock")
    public String deductTicket(){
        String lockKey = "ticket";


        // redis setnx 操作
        RLock lock = redisson.getLock(lockKey+"1");

        try {

            lock.lock();

            int ticketCount = Integer.parseInt(redisTemplate.opsForValue().get(lockKey));
            if (ticketCount > 0) {
                int realTicketCount = ticketCount - 1;
                log.info("扣除成功：剩余票数：" + realTicketCount);
                redisTemplate.opsForValue().set(lockKey, realTicketCount + "");
                return realTicketCount + "";
            } else {
                log.error("扣除失败");

            }
            return "end";
        } finally {
            lock.unlock();
        }

    }

}
